package cn.jdemo.juc.thread.阻塞与唤醒;

/**
 * 有锁，但是不是同一把锁
 * @see Thread#sleep(long) 让出cpu,其他线程可以使用cpu
 *
 */
public class Demo05 {
    private static final Object lock = new Object();
    public static void main(String[] args) throws InterruptedException {
        test01();
    }

    /**
     * 执行结果如下【同一把锁】
     * @see Object#wait()
     * @see Object#notify()
     * Thread-0start...
     * Thread-1start...
     * Thread-1end...
     * Thread-0end...
     */
    public static void test01() throws InterruptedException {
        Thread thread1 = new Thread(() -> {
            try {
                synchronized (lock) {
                    System.out.println(Thread.currentThread().getName() + "start...");
                    Thread.sleep(1000);
                    System.out.println(Thread.currentThread().getName() + "end...");
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        thread1.start();

        Thread.sleep(200L);// 保障线程1优先获取cpu

        Thread thread2 = new Thread(() -> {
            try {
                synchronized (lock) {
                    System.out.println(Thread.currentThread().getName() + "start...");
                    Thread.sleep(1000);
                    System.out.println(Thread.currentThread().getName() + "end...");
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        thread2.start();
        Thread.sleep(200L);
        Thread thread3 = new Thread(() -> {
            try {
                synchronized (lock) {
                    System.out.println(Thread.currentThread().getName() + "start...");
                    Thread.sleep(1000);
                    System.out.println(Thread.currentThread().getName() + "end...");
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        thread3.start();
    }
}
